<?php

/*    This file is part of ipmanage.

    ipmanage is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ipmanage is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ipmanage.  If not, see <http://www.gnu.org/licenses/>.
*/

function tableize_array($array){
	echo '<table>';
	foreach ($array as $col) {
		echo '<tr>';
		//foreach ($col as $row) {
			echo '<td>';
			echo $col;
			echo '</td>';
		//}
		echo '</tr>';
	}
	echo '</table>';
}

function db_getsettings(){
	global $db;
	$result = $db->getAssoc ("SELECT option_name, option_value FROM settings");
	return $result;
}

function db_getsetting($setting){
	global $db;
	global $sitesettings;
	if ($sitesettings[$setting]) {
		return ( $sitesettings[$setting] );
	} else {
			return ( $db ->getOne ('SELECT option_value FROM settings WHERE option_name = "'. $setting . '"') );
	}
}

function db_getiptable($subnet, $ip = ''){
	global $db;
	if (!($subnet=='')) {
		$sql = ('SELECT * FROM addresses WHERE NetID = "' . $subnet . '"' );  // Get the whole subnet
	} else {
		$sql = ('SELECT * FROM addresses WHERE IP = "' . $ip . '"' );
	}
		$results = $db->getAll ( $sql );

	return $results;
}
function db_buildsubnettable(){
	global $db;
		$que = $db->query('SELECT * FROM subnets');
		while ($results = $que->fetchRow ( DB_FETCHMODE_ASSOC )){
			?><tr>
			<td><?
			$url = make_get_url($_SERVER['PHP_SELF'], array ('mode' => 'shownet', 'NetID' => $results['NetID']));
			?><a href = "<?print $url;?>"><?print $results['NetID'];?></a>
			</td><td><?print $results['SNM'];?></td>
			<td><?print $results['scan_int'];?></td>
			</tr>
<?php
		}
}

function db_buildiptable($subnet){
		global $db;
		$que = $db->query('SELECT * FROM addresses WHERE NetID = "' . $subnet . '"');
		while ($results = $que->fetchRow ( DB_FETCHMODE_ASSOC )){
			?><tr>
			<td><?
			$url = make_get_url($_SERVER['PHP_SELF'], array ('mode' => 'showip', 'IP' => $results['IP']));
			?><a href = "' <?print $url;?> "> <?print $results['IP'];?></a>
			</td><td><?print $results['DNS'];?></td>
			</td><td><?print $results['last_seen'];?></td>
			</td><td><?print $results['status'];?></td>
			</td><td><?print $results['lock'];?></td>
			</tr>
<?php
		}
}

function make_get_url($page, $vars){
	$safe_vars = array();
	foreach ( $vars as $name => $value) {
		$safe_vars[ ] = urlencode($name).'='.urlencode($value);
	}
	$url = $page . '?' . join('&',$safe_vars);
	return $url;
}

function mask2cidr($mask) {
	strpos(decbin(ip2long($mask)), "0");
}

function insert_subnet($vars) {
	global $db;
     $pick_message = 'Selected category values<BR>are highlighted:';
     $sql  = 'INSERT INTO subnets (NetID, scan_int) VALUES (?, ?)';
     $params = array($vars['NetID'], $vars['scanint']);
     $query = $db->prepare($sql);
     if (DB::isError($query)) die("prepare: " . $query->getMessage(  ));
     $resp = $db->execute($query, $params);
     if (DB::isError($resp)) die("execute: " . $resp->getMessage(  ));
     $resp = $db->commit(  );
     if (DB::isError($resp)) die("commit: " . $resp->getMessage(  ));
     echo '<P CLASS="message">Record inserted as shown below.</P>';
     echo ($db->getOne('SELECT * FROM subnets WHERE NetID = "'.$vars['NetID'].'"'));
}
function subnet_walk($low, $high, $octet = 0, $prev=''){
	/* Recursive funcion - given a low end and high end of an IP range
	 returns an array containing all of the ips in the range
	 Example: 192.168.0.10 - 192.168.0.11
	Produces: [0] = 192.168.0.10; [1] = 192.168.0.11
	*/ 
	for ($counter =($low[$octet]); ($counter <= $high[$octet]); $counter++) {
		$prev[$octet] = $counter;
		if ($octet < (count($low) - 1)){
			$arr = subnet_walk($low, $high, ($octet+1),$prev);
		} else {
				$arr[] = (implode(".",$prev));
			}
		}
		return $arr;
}

function subnet_tiered_walk($low, $high, $octet = 0){
	/* Recursive funcion - given a low end and high end of an IP range
	 returns a recursive keyed array containing all of the ips in the range
	 Example: 192.168.0.10 - 192.168.0.12
	Produces:
				192{
						168{
								0{
									0
									1
									2
								}
							}
					}
	*/ 
	for ($counter =($low[$octet]); ($counter <= $high[$octet]); $counter++) {
			if ($octet < (count($low) - 1)){
				$arr[$counter] = subnet_walk($low, $high, ($octet+1));
			} else {
				$arr[$counter] = $counter;}
		}
		print $octet;
		echo_array($arr);
		return $arr;
}

function insert_ips($vars) {
	global $db;
	$low = explode('.', $vars['range'][0]);
	$high = explode('.', $vars['range'][1]);
	print "<br>";
	$ips = subnet_walk($low, $high);
	foreach ($ips as $ip){
		
     $sql  = 'INSERT INTO addresses (IP,NetID) VALUES (?,?)';
     $params = array($ip,$vars['NetID']);
     $query = $db->prepare($sql);
     if (DB::isError($query)) die("prepare: " . $query->getMessage(  ));
     $resp = $db->execute($query, $params);
     if (DB::isError($resp)) die("execute: " . $resp->getMessage(  ));

}
	$resp = $db->commit(  );
     if (DB::isError($resp)) die("commit: " . $resp->getMessage(  ));
     echo '<P CLASS="message">Record inserted as shown below.</P>';
     echo ($db->getOne('SELECT * FROM subnets WHERE NetID = "'.$vars['NetID'].'"'));

}

function checkNetmask4($ip) {
  $ip2long = ip2long($ip);
  $decbin = decbin($ip2long);
  if ($ip2long === FALSE) {
    return false;
  } elseif(strlen($decbin) != 32 && $ip2long != 0) {
    return false;
  } elseif(ereg('01',$decbin)) {
    return false;
  } else {
    return true;
  }
}

function subnet_low_high($base, $bits){
       /* get the base and the bits from the ban in the database */
print ($base . $bits);
        /* now split it up into it's classes */
        list($a, $b, $c, $d) = explode('.', $base);

        /* now do some bit shfiting/switching to convert to ints */
        $i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
        $mask = $bits == 0 ? 0 : (~0 << (32 - $bits));

        /* here's our lowest int */
        $low = $i & $mask;

        /* here's our highest int */
        $high = $i | (~$mask & 0xFFFFFFFF);
		return (array(long2ip($low),long2ip($high)));

        /* now split the ip were checking against up into classes */
      /*  list($a, $b, $c, $d) = explode('.', $iptocheck);

        /* now convert the ip we're checking against to an int */
        /*$check = ($a << 24) + ($b << 16) + ($c << 8) + $d;*/

        /* if the ip is within the range, including
      highest/lowest values, then it's witin the CIDR range */
      /*  if ($check >= $low && $check <= $high)
            return (array(long2ip($low),long2ip($high)));
       else
            return 0;*/
}
function split_cidr($subnet){
	require ("IPv4.php");
	$nub = new Net_IPv4();
	$subnet = (explode("/", $subnet));
	$netmask = $nub->getNetmask($subnet[1]);
	$ip = $nub->getSubnet($subnet[0],$netmask);
	return (array ('NetID'=>$ip, 'SNM'=>$netmask, 'CIDR'=>$subnet[1]));
	}
	
	
	function echo_array($array,$return_me=false){
    if(is_array($array) == false){
        $return = "The provided variable is not an array.";
    }else{
        foreach($array as $name=>$value){
            if(is_array($value)){
                $return .= "";
                $return .= "['<b>$name</b>'] {<div style='margin-left:10px;'>\n";
                $return .= echo_array($value,true);
                $return .= "</div>}";
                $return .= "\n\n";
            }else{
                if(is_string($value)){
                    $value = "\"$value\"";
                }
                $return .= "['<b>$name</b>'] = $value\n\n";
            }
        }
    }
    if($return_me == true){
        return $return;
    }else{
        echo "<pre>".$return."</pre>";
    }
}
?>